package cmd

import (
	"fmt"
	"log"
	"net/http"
	"runtime/debug"

	"github.com/gin-contrib/pprof"
	"github.com/gin-gonic/gin"
	swaggerfiles "github.com/swaggo/files"
	ginswagger "github.com/swaggo/gin-swagger"
	"qmp_go_push/conf"
	"qmp_go_push/middleware"
	"qmp_go_push/pkg/grpc"
	"qmp_go_push/pkg/socket"
	"qmp_go_push/router/api"
	"qmp_go_push/router/websocket"
)

func initServe() {
	// SetPanicOnFault允许这些程序请求运行时只触发一个panic，而不是崩溃。SetPanicOnFault只用于当前的go程
	debug.SetPanicOnFault(true)
	gin.SetMode(conf.CONFIG.Server.RunMode)
	// 创建Gin实例
	engine := gin.New()
	// Gin中间件校验
	engine.Use(gin.Recovery(), middleware.CrossDomain(), middleware.ParseJson())

	// 注册Http路由
	api.RegisterRouters(engine)
	// 注册pprof，使用方式：go tool pprof -web https://域名/im/pprof/profile
	pprof.Register(engine, "todo/pprof")
	// 注册swagger接口文档
	engine.GET("/todo/swagger/*any", ginswagger.WrapHandler(swaggerfiles.Handler))

	// 注册websocket路由
	websocket.RegisterRouters()
	// 开始websocket定时清理任务
	socket.StartCleanConnTask()
	// 启动websocket
	go socket.InitServer()

	// 启动rpc
	go grpc.InitServer()

	// 启动http服务
	if err := http.ListenAndServe(fmt.Sprintf(":%d", conf.CONFIG.Server.HttpPort), engine); err != nil {
		log.Fatal("Fatal error http.ListenAndServe(httpPort int): \n", err.Error())
	}
}
